package manager

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/jmoiron/sqlx"
)

// DBX mapper dbrouter DB
type DBX struct {
	*sqlx.DB
}

var manager *Manager

const (
	DB_TYPE_MYSQL = "mysql"
)

func InitManager(ctx context.Context, mgr *Manager) error {
	manager = mgr
	return nil
}

func GetDB(ctx context.Context, cluster string) (*DB, error) {
	return manager.GetDB(ctx, cluster)
}

// NamedExecWrapper ...
func (db *DBX) NamedExecWrapper(tables []interface{}, query string, arg interface{}) (sql.Result, error) {
	query = fmt.Sprintf(query, tables...)
	return db.DB.NamedExec(query, arg)
}

// NamedQueryWrapper ...
func (db *DBX) NamedQueryWrapper(tables []interface{}, query string, arg interface{}) (*sqlx.Rows, error) {
	query = fmt.Sprintf(query, tables...)
	return db.DB.NamedQuery(query, arg)
}

// SelectWrapper ...
func (db *DBX) SelectWrapper(tables []interface{}, dest interface{}, query string, args ...interface{}) error {
	query = fmt.Sprintf(query, tables...)
	return db.DB.Select(dest, query, args...)
}

// ExecWrapper ...
func (db *DBX) ExecWrapper(tables []interface{}, query string, args ...interface{}) (sql.Result, error) {
	query = fmt.Sprintf(query, tables...)
	return db.DB.Exec(query, args...)
}

// NamedQueryWrapper ...
func (db *DBX) QueryRowxWrapper(tables []interface{}, query string, args ...interface{}) *sqlx.Row {
	query = fmt.Sprintf(query, tables...)
	return db.DB.QueryRowx(query, args...)
}

// QueryxWrapper ...
func (db *DBX) QueryxWrapper(tables []interface{}, query string, args ...interface{}) (*sqlx.Rows, error) {
	query = fmt.Sprintf(query, tables...)
	return db.DB.Queryx(query, args...)
}

// GetWrapper ...
func (db *DBX) GetWrapper(tables []interface{}, dest interface{}, query string, args ...interface{}) error {
	query = fmt.Sprintf(query, tables...)
	return db.DB.Get(dest, query, args...)
}
